package com.softserveinc.ita.kaiji.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.softserveinc.ita.kaiji.model.Card;
import com.softserveinc.ita.kaiji.model.Deck;
import com.softserveinc.ita.kaiji.model.game.Game;
import com.softserveinc.ita.kaiji.model.game.GameHistory;
import com.softserveinc.ita.kaiji.model.game.GameInfo;
import com.softserveinc.ita.kaiji.model.player.Player;
import com.softserveinc.ita.kaiji.model.game.RoundResult;
import com.softserveinc.ita.kaiji.service.GameService;
import com.softserveinc.ita.kaiji.service.GameServiceImpl;

/**
 * @author Eugene Semenkov
 * @since 17.03.14
 */

@Controller
@RequestMapping("/game")
public class PlayGameController {
	
	private static final Logger logger = Logger.getLogger(PlayGameController.class);
	
	private GameService gameService = new GameServiceImpl();

	@RequestMapping(value = "/{gameId}/", method = {RequestMethod.GET, RequestMethod.POST})
	public String initGame(@PathVariable Integer gameId,
			@CookieValue("personId") Integer personId,
			Model model) {
		
		logger.info("Starting initGame. GameId: " + gameId + ". PersonId: " + personId);
        
        GameHistory gameHistory = gameService.getGameHistory(gameId);
        
        List<RoundResult> roundResults = gameHistory.getRoundResults();
        
        GameInfo gameInfo = gameHistory.getGameInfo();
        
        Set<Player> players = gameInfo.getPlayers();
        Player person = null;
        Player enemy = null;
        
        for(Player player : players) {
            
            if(player.isBot()){

                enemy = player;
                
            }else{
                
                person = player;
                
            }
            
        }
        
        Deck personDeck = person.getDeck();
        Deck enemyDeck = enemy.getDeck();
        
        HashMap<Card, Integer> playerDeckCardCount = new HashMap<Card, Integer>();
        HashMap<Card, Integer> enemyDeckCardCount = new HashMap<Card, Integer>();
        
        for(Card card : Card.values()){
            
            playerDeckCardCount.put(card, personDeck.getCardTypeCount(card));
            enemyDeckCardCount.put(card, enemyDeck.getCardTypeCount(card));
            
        }

        Map<Card.DuelResult, Integer> statistic = gameHistory.getStatisticFor(person);
                
        RoundResult lastRoundResult = gameHistory.getLastRoundResult();

    	Card playerChosenCard = null;
        Card enemyChosenCard = null;
        
        if(lastRoundResult != null) {
        	
        	playerChosenCard = lastRoundResult.getCard(person);
	        enemyChosenCard = lastRoundResult.getCard(enemy);
        	
        }
        
//        logger.info(lastRoundResult.getCard(enemy));
        
        boolean gameIsFinished = gameHistory.getGameStatus() == Game.State.GAME_FINISHED;
        
        boolean isPlayerWinner = false;
        boolean isEnemyWinner = false;
        
        if(gameIsFinished) {
        	
        	Player winner = gameHistory.getWinner();
        	
        	if(winner == null) {
        		
        		isPlayerWinner = false;
        		isEnemyWinner = false;
        		
        	}else {
        		
        		Integer winnerId = winner.getId();
        	
	        	if(winnerId == null) {
	        	
	        		isPlayerWinner = false;
	        		isEnemyWinner = false;
	        	
	        	}else {
	        		        		
	        		isPlayerWinner = winnerId.equals(person.getId());
	        		isEnemyWinner = winnerId.equals(enemy.getId());
	        		
	        	}
	        	
        	}
        	
        }

        model.addAttribute("player", person);
        model.addAttribute("enemyPlayer", enemy);
        model.addAttribute("playerDeck", playerDeckCardCount);
        model.addAttribute("enemyDeck", enemyDeckCardCount);
        model.addAttribute("statistic", statistic);
        model.addAttribute("rounds", roundResults);
        model.addAttribute("playerChosenCard", playerChosenCard);
        model.addAttribute("enemyChosenCard", enemyChosenCard);
        model.addAttribute("isFinished", gameIsFinished);
        model.addAttribute("isPlayerWinner", isPlayerWinner);
        model.addAttribute("isEnemyWinner", isEnemyWinner);
        model.addAttribute("gameId", gameId);
        
        return "play-game";

	}

	@RequestMapping(value = "/{gameId}/card/{cardName}/", method = RequestMethod.GET)
	public String getCard(@PathVariable Integer gameId,
			@PathVariable String cardName,
			@CookieValue("personId") Integer personId,
			Model model) {

		logger.info("Starting getCard. GameId: " + gameId + ". CardId: " + cardName + ". PersonId: " + personId);
		
		Card playerChosenCard = null;
		for(Card card : Card.values()) {	
			
			if(card.name().equals(cardName)) {
				
				playerChosenCard = card;
				
			}			
			
		}
		
		gameService.makeTurn(gameId, personId, playerChosenCard);

		return "forward:/game/"+gameId+"/";

	}

}
